package com.drinks.yiniang.ui.activity.conversation;

import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;

import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.listview.ServiceChatAdapter;
import com.drinks.yiniang.entity.message.ChatJson;
import com.drinks.yiniang.entity.message.SendChatMsgJson;
import com.drinks.yiniang.io.api.MessageApiIO;
import com.drinks.yiniang.ui.widget.layout.ServiceChatInputLayout;
import com.drinks.yiniang.utils.KeyBoardUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.listview.AutoLoadMoreListView;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 客服会话页面
 *
 * @author han
 * @date 2019-11-01
 */
public class ServiceChatActivity extends BaseTranBarActivity implements OnNavgationBarClickListener,
        AutoLoadMoreListView.OnLoadMoreListener, ServiceChatInputLayout.OnChatSendClickListener {

    //nav
    private NavigationBarLayout nav_bar_service_chat;
    private AutoLoadMoreListView lv_service_chat;
    private ServiceChatInputLayout ll_chat_input;

    private ServiceChatAdapter mServiceChatAdapter;

    private List<ChatJson.ChatList> mList;


    //聊天对象id
    private String mTargetUserId;
    //聊天对象昵称
    private String mNavTitle;
    //是否是和客服聊天
    private boolean isCustomerServiceChat;

    private int mPages;

    @Override
    protected void initView() {
        nav_bar_service_chat = findViewById(R.id.nav_bar_service_chat);

        lv_service_chat = findViewById(R.id.lv_service_chat);

        ll_chat_input = findViewById(R.id.ll_chat_input);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        getWindow().setBackgroundDrawable(ContextCompat.getDrawable(mContext, R.color.white));

        if (getIntent() != null) {
            mTargetUserId = getIntent().getStringExtra(Constants.KeyUserId);
            isCustomerServiceChat = getIntent().getBooleanExtra(Constants.KeyBoolen, false);
            mNavTitle = getIntent().getStringExtra(Constants.KeyTitle);
        }

        nav_bar_service_chat.setNavBarTitle(mNavTitle);

        KeyBoardUtils.assistActivity(this);
        initAdapter();

        getChatMessage();
    }

    private void initAdapter() {
        mList = new ArrayList<>();

        mServiceChatAdapter = new ServiceChatAdapter(mContext, mList);
        mServiceChatAdapter.setIsCustomerServiceChat(isCustomerServiceChat);

        lv_service_chat.setAdapter(mServiceChatAdapter);
    }

    @Override
    protected void initListener() {
        nav_bar_service_chat.setOnNavgationBarClickListener(this);
        lv_service_chat.setOnLoadMoreListener(this);
        ll_chat_input.setOnChatSendClickListener(this);
    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_service_chat;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {//全部已读

    }

    @Override
    public void onChatSendClick(String content) {
        sendMessage(content);
    }

    //发送消息
    private void sendMessage(String content) {
        if (StringUtils.isEmpty(content)) {
            return;
        }

        if (isCustomerServiceChat) {//发送客服消息
            sendCustomerServiceMsg(content);
            return;
        }

        if (StringUtils.isEmpty(mTargetUserId)) {
            ToastUtils.showShort(R.string.text_user_not_exist);
            return;
        }

        showLoadingDialog();

        MessageApiIO.getInstance().sendPrivateMessage(mTargetUserId, content, new APIRequestCallback<SendChatMsgJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(SendChatMsgJson res) {
                if (mList == null) {
                    return;
                }

                //清除输入框内容
                ll_chat_input.setEditTextValue(null);

                ChatJson.ChatList data = new ChatJson.ChatList();

                data.setContent(res.getData().getContent());
                data.setCreated_at(res.getData().getCreated_at());
                data.setType(ServiceChatAdapter.TYPE_CHAT_MSG_RIGHT);
                data.setId(res.getData().getId());

                ChatJson.ChatList timeData = new ChatJson.ChatList();
                timeData.setCreated_at(data.getCreated_at());

                mList.add(timeData);
                mList.add(data);

                mServiceChatAdapter.notifyDataSetChanged();
                lv_service_chat.setSelection(mList.size());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //发送客服消息
    private void sendCustomerServiceMsg(String content) {
        showLoadingDialog();

        MessageApiIO.getInstance().sendCustomerServiceMsg(content, new APIRequestCallback<SendChatMsgJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(SendChatMsgJson res) {
                if (mList == null) {
                    return;
                }

                //清除输入框内容
                ll_chat_input.setEditTextValue(null);

                ChatJson.ChatList data = new ChatJson.ChatList();

                data.setService_fans_id(res.getData().getService_fans_id());
                data.setContent(res.getData().getContent());
                data.setSend_time(res.getData().getSend_time());
                data.setType(ServiceChatAdapter.TYPE_CHAT_MSG_RIGHT);
                data.setId(res.getData().getId());

                ChatJson.ChatList timeData = new ChatJson.ChatList();
                timeData.setSend_time(data.getSend_time());

                mList.add(timeData);
                mList.add(data);
                mServiceChatAdapter.notifyDataSetChanged();
                lv_service_chat.setSelection(mList.size());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    @Override
    public void onLoadMore() {
        if (isCustomerServiceChat) {
            getMoreCustomerServiceMessage();
            return;
        }

        MessageApiIO.getInstance().getMessageChatList(mTargetUserId, mPages, new APIRequestCallback<ChatJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(ChatJson res) {
                loadDataComplete(res.getData().getData(), true);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                lv_service_chat.onLoadMoreComplete(false);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void getChatMessage() {
        if (isCustomerServiceChat) {
            getCustomerServiceMessage();
            return;
        }

        if (StringUtils.isEmpty(mTargetUserId)) {
            ToastUtils.showShort(R.string.text_user_not_exist);
            return;
        }

        showLoadingDialog();

        mPages = 1;

        MessageApiIO.getInstance().getMessageChatList(mTargetUserId, mPages, new APIRequestCallback<ChatJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(ChatJson res) {
                loadDataComplete(res.getData().getData(), false);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                lv_service_chat.onLoadMoreComplete(false);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void getMoreCustomerServiceMessage() {
        MessageApiIO.getInstance().getCustomerServiceMsgList(mPages, new APIRequestCallback<ChatJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(ChatJson res) {
                loadDataComplete(res.getData().getData(), true);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                lv_service_chat.onLoadMoreComplete(false);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void getCustomerServiceMessage() {
        showLoadingDialog();

        mPages = 1;

        MessageApiIO.getInstance().getCustomerServiceMsgList(mPages, new APIRequestCallback<ChatJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(ChatJson res) {
                loadDataComplete(res.getData().getData(), false);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                lv_service_chat.onLoadMoreComplete(false);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void loadDataComplete(List<ChatJson.ChatList> ls, boolean isLoadMore) {
        if (mServiceChatAdapter == null || ls == null) {
            return;
        }

        mPages++;

        lv_service_chat.onLoadMoreComplete(CommonUtils.isHasMoreData(ls));

        ChatJson.ChatList timeData, tempData;

        if (isLoadMore) {
            for (int i = ls.size() - 1; i >= 0; i--) {
                tempData = ls.get(i);

                timeData = new ChatJson.ChatList();
                timeData.setSend_time(tempData.getSend_time());
                timeData.setCreated_at(tempData.getCreated_at());

                mList.add(0, tempData);
                mList.add(0, timeData);
            }
            lv_service_chat.setStackFromBottom(false);
            lv_service_chat.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_DISABLED);
        } else {
            for (int i = 0; i < ls.size(); i++) {
                tempData = ls.get(i);

                timeData = new ChatJson.ChatList();

                timeData.setSend_time(tempData.getSend_time());
                timeData.setCreated_at(tempData.getCreated_at());

                mList.add(timeData);
                mList.add(tempData);
            }

            lv_service_chat.resetListViewStack();
        }

        int fVisiblePos = lv_service_chat.getFirstVisiblePosition();

        mServiceChatAdapter.notifyDataSetChanged();

        if (isLoadMore) {
            if (fVisiblePos == 0) lv_service_chat.setSelection(ls.size());
        }
    }
}
